import time

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

time_wait = 1


def ini_chrome():
    opt = Options()
    # 通过option参数，设置浏览器不关闭
    opt.add_experimental_option('detach', True)
    # 去掉 Chrome正受到自动测试软件的控制
    opt.add_experimental_option("excludeSwitches", ['enable-automation'])
    web = Chrome(options=opt)
    # 窗口最大化
    web.maximize_window()
    web.implicitly_wait(10)
    return web


def get_data(url):
    web = ini_chrome()
    web.get(url)
    title = web.title
    print(f'标题：{title}，类型：{type(title)}')
    if title is None or len(title) == 0:
        print(f'-----首次加载失败，重新加载-,休眠{time_wait}秒-------')
        time.sleep(time_wait)
        # 刷新页面
        web.refresh()
    # 设置等待
    wait = WebDriverWait(web, 10)
    # 模拟下拉滚动条，将页面滚动到底部
    wait.until(EC.title_contains('Amazon Best Sellers'))
    div_roots = web.find_elements(By.ID, 'gridItemRoot')
    div_len = len(div_roots)
    while div_len < 50:
        div_roots = web.find_elements(By.ID, 'gridItemRoot')
        div_len = len(div_roots)
        print(f'采集数据：{len(div_roots)}')
        if div_len == 50:
            break
        time.sleep(1)
        target = web.find_elements(By.XPATH, '//*[@id="gridItemRoot"]')[div_len - 1]
        actions = ActionChains(web)
        actions.move_to_element(target)
        actions.perform()
    # web.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    print(f'滚动热销页面结束，共{len(div_roots)}条')
    pre_url = 'https://www.amazon.com'
    # 标题 asin 价格 评分 review 上架时间 上架天数 图片
    for p in div_roots:
        pai_ming = p.find_element(By.CLASS_NAME, 'zg-bdg-text').text
        asin = p.find_element(By.CLASS_NAME, 'p13n-sc-uncoverable-faceout').get_attribute('id')
        img_url = p.find_element(By.TAG_NAME, 'img').get_attribute('src')
        detail_url = p.find_elements(By.TAG_NAME, 'a')[0].get_attribute('href')
        title = p.find_element(By.CLASS_NAME, '_cDEzb_p13n-sc-css-line-clamp-3_g3dy1').text
        score = p.find_element(By.CLASS_NAME, 'a-icon-row').find_elements(By.CLASS_NAME, 'a-icon-alt')[0].get_attribute(
            'innerHTML')
        review = p.find_element(By.CLASS_NAME, 'a-icon-row').find_elements(By.TAG_NAME, 'span')[1].get_attribute(
            'innerHTML')
        price = p.find_element(By.CLASS_NAME, '_cDEzb_p13n-sc-price_3mJ9Z').get_attribute('innerHTML')
        print(
            f'排名：{pai_ming},ASIN：{asin},图片：{img_url},详情链接：{detail_url},标题：{title},评分：{score}，review：{review},价格：{price}')
        # print(p.find_element(By.CLASS_NAME, 'a-icon-row').get_attribute('innerHTML'))
        # for span in p.find_element(By.CLASS_NAME, 'a-icon-row').find_elements(By.TAG_NAME, 'span'):
        #     print(span.get_attribute('innerHTML'))
        #     print(span.text)
        #     print('==============')
        #
        # print('------------')
        # score = p.find_element(By.CLASS_NAME, 'a-icon-row').find_element(By.XPATH, '//span[@class="a-icon-alt"]').get_attribute('innerHTML')
        # print(score)
        new_tab = f'window.open("{detail_url}");'
        print(new_tab)
        web.execute_script(new_tab)
        # 注意，在selenium的眼中，新窗口默认是不切换过来的，
        web.switch_to.window(web.window_handles[-1])
        time.sleep(2)
        # 查询商品详情

        # 关掉子窗口
        web.close()
        # 回到原来得窗口中
        web.switch_to.window(web.window_handles[0])


def title_err(title):
    error_title = 'amazon.com'
    error_t2 = 'www.amazon.com'
    if title is None:
        return False
    elif len(title) == 10 and title.lower() == error_title:
        return False
    elif len(title) == 14 and title.lower() == error_t2:
        return False


def refresh_loc(web):
    # 切换地址
    wait = WebDriverWait(web, 5)
    # 判断元素是否出现
    locator = (By.ID, 'nav-packard-glow-loc-icon')
    wait.until(EC.presence_of_element_located(locator))
    web.find_element(By.ID, 'nav-packard-glow-loc-icon').click()
    locator2 = (By.ID, 'GLUXZipUpdateInput')
    wait.until(EC.presence_of_element_located(locator2))
    web.find_element(By.ID, 'GLUXZipUpdateInput').send_keys('10001')
    time.sleep(0.5)
    web.find_element(By.ID, 'GLUXZipUpdate').click()
    time.sleep(0.5)
    # script = '$("#GLUXConfirmClose").click();'
    # web.execute_script(script)
    # # 刷新页面
    # time.sleep(2)
    # all_handles = web.window_handles
    # print('所有弹窗')
    # print(all_handles)
    ActionChains(web).click().perform()
    time.sleep(0.5)
    web.refresh()
    time.sleep(0.5)


def detail(url):
    web = ini_chrome()
    web.get(url)
    title = web.title
    if not title_err(title):
        print(f'-----首次加载失败，重新加载-,休眠{time_wait}秒-------')
        time.sleep(time_wait)
        # 刷新页面
        web.refresh()
    time.sleep(0.5)
    loca = web.find_element(By.ID, 'glow-ingress-line2').get_attribute('innerHTML')
    print(f'切换之前位置：{loca}')
    print(f'标题：{title}')
    refresh_loc(web)
    loca2 = web.find_element(By.ID, 'glow-ingress-line2').get_attribute('innerHTML')
    print(f'切换之后位置：{loca2}')
    # wait.until(EC.alert_is_present())
    # alert = web.switch_to.alert
    # text = alert.text
    # alert.accept()
    # print(f'弹出框:{text}')
    print('+++++++++++++++处理地址切换 END+++++++++++++++++')
    # locator3 = (By.ID, 'GLUXConfirmClose')
    # wait.until(EC.presence_of_element_located(locator3))
    # GLUXConfirmClose = web.find_element(By.ID, 'GLUXConfirmClose').get_attribute('innerHTML')
    # print(GLUXConfirmClose)


    # 商品规格表单
    try:
        norm_form = web.find_element(By.ID, 'twister')
    except:
        print("====该商品没有配置规格，直接进行详情提取=======")
    color_arr = []
    size_arr = []

    desc = ''
    # 五点描述
    try:
        feature = web.find_element(By.ID, 'feature-bullets')
        li_list = feature.find_element(By.TAG_NAME, 'ul').find_elements(By.TAG_NAME, 'li')
        for li in li_list:
            descri = li.find_element(By.TAG_NAME, 'span').get_attribute('innerHTML')
            desc += (descri + '\n')
            print(desc)
    except Exception as e:
        print('该商品没有五点描述', str(e))

    ul_list = norm_form.find_elements(By.TAG_NAME, 'ul')
    for ul in ul_list:

        # print(ul.get_attribute("innerHTML"))
        # 获取该ul标签下的 li 标签
        li_list = ul.find_elements(By.TAG_NAME, 'li')
        # 判断改li标签的属性
        print('++++++++++innerHTML+++++++++++++')
        for li in li_list:
            innerHtml = li.get_attribute('innerHTML')
            # print(innerHtml)
            print('<img' in innerHtml)
            print('<p' in innerHtml)
            # try:
            #     img_url = li.find_element(By.TAG_NAME, 'img').get_attribute('src')
            #     print(f'img_url: {img_url}')
            # except:
            #     print('不是颜色节点')
            #     size_info = li.find_element(By.TAG_NAME, 'p').text
            #     print(f'规格：{size_info}')
    # try:
    #     img_urls = ul.find_elements(By.TAG_NAME, 'img')
    #     for img_url in img_urls:
    #         img = img_url.get_attribute('src')
    #         color_arr.append(img)
    #     try:
    #         price = ul.find_element(By.TAG_NAME, 'p').text
    #         print(f'价格：{price}')
    #         color_arr.append(str(price))
    #     except:
    #         print('改产品变体没有配置价格')
    #         pass
    # except:
    #     # 不是图片，运行规格代码
    #     size_list = ul.find_elements(By.TAG_NAME, 'p')
    #     for size in size_list:
    #         size_info.append(size.text)
    #     pass
    # print(f'颜色：{color_arr},规格：{size_info}')
    # print(norm_form.get_attribute('innerHTML'))
    # 获取颜色 color : variation_color_name
    # try:
    #     color_div = norm_form.find_element(By.ID, 'variation_color_name')
    #     if color_div is not None:
    #         color_list = color_div.find_elements(By.TAG_NAME, 'li')
    #         for color in color_list:
    #             img_url = color.find_element(By.TAG_NAME, 'img').get_attribute('src')
    #             try:
    #                 price = color.find_element(By.TAG_NAME, 'p').text
    #                 print(f'价格：{price}')
    #             except:
    #                 print('改产品变体没有配置价格')
    #                 pass
    #             print(f'规格图片路径：{img_url}')
    # except:
    #     pass

    # size : variation_style_name
    # size_list = norm_form.find_element(By.ID, 'variation_style_name')
    # style: variation_size_name
    # try:
    #     size_div = norm_form.find_element(By.ID, 'variation_size_name')
    #     if size_div is not None:
    #         size_list = size_div.find_elements(By.TAG_NAME, 'li')
    #         for size in size_list:
    #             size = size.find_element(By.TAG_NAME, 'p').text
    #             print(f'尺寸：{size}')
    # except:
    #     pass
    # 商品简述： productOverview_feature_div
    # productOverview = web.find_element(By.ID, 'productOverview_feature_div')
    # tr_list = productOverview.find_elements(By.TAG_NAME, 'tr')
    # for tr in tr_list:
    #     attr_name = tr.find_element(By.CLASS_NAME, 'a-span3').find_element(By.TAG_NAME, 'span').get_attribute(
    #         'innerHTML')
    #     attr_value = tr.find_element(By.CLASS_NAME, 'a-span9').find_element(By.TAG_NAME, 'span').get_attribute(
    #         'innerHTML')
    #     print(f"{attr_name}:::{attr_value}")

    # div_list = norm_form.find_elements(By.XPATH, '/div')
    # for div in div_list:
    #     print(div.get_attribute('innerHTML'))
    # 商品详情：productDetails_feature_div
    # print('+++商品详情+++')
    # detail_info = {}
    # product_details = web.find_element(By.ID, 'productDetails_feature_div')
    # table_list = product_details.find_elements(By.TAG_NAME, 'table')
    # for table in table_list:
    #     for tr in table.find_elements(By.TAG_NAME, 'tr'):
    #         d_attr_name = tr.find_element(By.TAG_NAME, 'th').text
    #         d_attr_value = tr.find_element(By.TAG_NAME, 'td').text
    #         detail_info[d_attr_name] = d_attr_value
    # print(f'详情信息：{detail_info}')


if __name__ == '__main__':
    pageNum = 1
    url = f'https://www.amazon.com/Best-Sellers-Home-Kitchen-Free-Standing-Shoe-Racks/zgbs/home-garden/11601913011/ref=zg_bs_pg_{pageNum}_home-garden?_encoding=UTF8&pg={pageNum}'
    detail_url = 'https://www.amazon.com/KEETDY-Entryway-Organizer-Stackable-Sneakers/dp/B09XD65GST/ref=zg_bs_g_11601913011_sccl_46/134-1260813-3246429?th=1'
    # get_data(url)
    detail(
        'https://www.amazon.com/Suwoic-Cabinet-Entryway-Storage-Freestanding/dp/B0BX9DJ7LY/ref=sr_1_1?keywords=B0BX9DJ7LY&qid=1697707921&s=hi&sr=1-1')
